<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">

        <el-form-item label="年级：" prop="level">
            <el-select  clearable v-model="ruleForm.level" placeholder="年级" @change="levelChange">
                <el-option :label="item.name" :value="item.value" v-for="item in levelStore.list" :key="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="学科: " prop="subject">
            <el-select clearable v-model="ruleForm.subjectId" placeholder="请选择" size="large">
                <el-option v-for="item in filterSubjectByLevel(arr, ruleForm.level)" :key="item.id" :label="item.name + '(' + item.levelName + ')'" :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="试卷类型：" prop="paperType">
            <el-select v-model="ruleForm.paperType" placeholder="固定试卷">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="试卷名称:" prop="name">
            <el-input clearable v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="考试时间:" prop="suggestTime">
            <el-input clearable v-model="ruleForm.suggestTime" placeholder="分钟" />
        </el-form-item>
        <el-form-item v-for="(item, idx) in titleItems" :key="idx" :label="`标题${idx+1}`" required>
          <el-input v-model="item.name" placeholder="请输入大题标题" style="width: 70%" />
          <el-button type="text" @click="() => openQuestionDialog(idx)">添加题目</el-button>
          <el-button type="text" @click="removeTitle(idx)" v-if="titleItems.length > 1" style="color: #409EFF">删除</el-button>
          <div v-if="item.questionItems.length" class="added-question-list">
            <div v-for="(q, qidx) in item.questionItems" :key="q.id" class="added-question-card">
              <div class="added-question-row">
                <span class="added-question-label">{{ String.fromCharCode(65 + qidx) }}</span>
                <span class="added-question-id">{{q.id}}</span>
                <span class="added-question-type">{{ questionTypes.find(t => t.value === q.type)?.label || q.type }}</span>
                <el-button type="text" class="added-question-remove" @click="item.questionItems.splice(qidx, 1)">删除</el-button>
              </div>
              <div class="added-question-title">{{q.title}}</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            <el-button @click="addTitle">添加标题</el-button>
        </el-form-item>

    <el-dialog v-model="showQuestionDialog" title="添加题目" width="500px">
      <el-form label-width="60px">
        <el-form-item label="ID：">
          <el-input v-model="questionForm.id" />
        </el-form-item>
        <el-form-item label="题型：">
          <el-select v-model="questionForm.type" placeholder="请选择">
            <el-option v-for="item in questionTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryQuestions">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="questionList" style="width: 100%; margin-bottom: 10px;">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="shortTitle" label="题干" />
        <el-table-column label="题型">
          <template #default="scope">
            {{ questionTypes.find(t => t.value === scope.row.questionType)?.label || scope.row.questionType }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="addQuestionToTitle(scope.row)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeQuestionDialog">取消</el-button>
      </span>
    </el-dialog>
    </el-form>

    <!-- 题目弹框 -->
    <el-dialog title="题目列表" :visible.sync="showQuestionDialog" width="60%">
      <div>
        <el-form :model="questionForm" label-width="100px" class="question-form">
          <el-form-item label="题目类型：" prop="type">
            <el-select v-model="questionForm.type" placeholder="请选择题目类型">
              <el-option
                v-for="item in questionTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="queryQuestions">查询题目</el-button>
        <el-table :data="questionList" style="width: 100%" v-if="questionList.length">
          <el-table-column prop="id" label="题目ID" />
          <el-table-column prop="title" label="题目内容" />
          <el-table-column prop="type" label="题目类型" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="mini" @click="addQuestionToTitle(row)">添加到标题</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else>暂无题目数据</div>
      </div>
      <template #footer>
        <el-button @click="closeQuestionDialog">关闭</el-button>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useLevelStore } from "@/stores/level"
import { examAdd, type ExamAddParamsType } from "@/api/exampage"
import { useRouter, useRoute } from "vue-router"
import axios from 'axios'
import { QuestiontPage, type QuestionType } from "@/api/examques"
//创建路由实例
const router = useRouter()
const route = useRoute()
const options = [
    { value: 4, label: '固定试卷' },
    { value: 5, label: '时段试卷' },
    { value: 6, label: '任务试卷' }
]
const arr = ref<any>([])
const id = ref('')

function getsubjectList() {
    axios({
        url: "/api/api/admin/education/subject/list",
        method: "post",
    }).then(res => {
        console.log(res.data, 'subject')
        if (res.data.message == "成功") {
            arr.value = res.data.response
        }
    })

}
getsubjectList()

const subject = ref('')

//pinia 年级的数据
const levelStore = useLevelStore()
//获取elFrom组件
const ruleFormRef = ref<FormInstance>()
//添加的表单数据
const ruleForm = ref<ExamAddParamsType>({
    id: null,
    level: '',
    subjectId: '',
    paperType: '',
    levelName: '',
    name: '',
    suggestTime: ''
})
//验证规则
const rules = ref<FormRules<ExamAddParamsType>>({
    name: [
        { required: true, message: '请输入试卷名称', trigger: 'blur' },
    ],
    level: [
        { required: true, message: '请选择年级', trigger: 'blur' },
    ],
    subjectId: [
        { required: true, message: '请选择学科', trigger: 'change' },
    ],
    paperType: [
        { required: true, message: '请选择试卷类型', trigger: 'change' },
    ],
    suggestTime: [
        { required: true, message: '请输入考试时间', trigger: 'blur' },
        // { type: 'number', message: '考试时间必须为数字', trigger: 'blur' }
    ]
})
//年级变化的事件
function levelChange(val: any) {
    const level = levelStore.list.find(item => item.value == val)
    ruleForm.value.levelName = (level?.name as string)
}
//标题项
interface QuestionItem {
  id: number | string
  type: number | string
  title: string
  subjectId: number | string
  analyze: string
  score: number
  questionType: number | string
}
interface TitleItem {
  name: string
  questionItems: QuestionItem[]
}
const titleItems = ref<TitleItem[]>([
  { name: '', questionItems: [] }
])

function addTitle() {
  titleItems.value.push({ name: '', questionItems: [] })
}
function removeTitle(index: number) {
  titleItems.value.splice(index, 1)
}
//添加功能
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 提交前类型转换
    ruleForm.value.suggestTime = Number(ruleForm.value.suggestTime)
    ruleForm.value.paperType = Number(ruleForm.value.paperType)
    ruleForm.value.subjectId = Number(ruleForm.value.subjectId)
    ruleForm.value.level = Number(ruleForm.value.level)
    // 保证所有题目 analyze 不为空且所有字段类型正确
    titleItems.value.forEach(title => {
      title.questionItems.forEach(q => {
        q.analyze = String(q.analyze || '无')
        q.subjectId = Number(q.subjectId ?? ruleForm.value.subjectId)
        q.score = Number(q.score ?? 0)
        q.questionType = Number(q.questionType ?? q.type ?? 0)
        q.type = Number(q.type ?? q.questionType ?? 0)
        q.id = Number(q.id)
        q.title = String(q.title || '')
      })
    })
    // 保证 titleItems 结构正确
    if (!titleItems.value.length || titleItems.value.some(t => !t.name || !t.questionItems.length)) {
      ElMessage.error('请完善每个大题标题和题目')
      return
    }
    await formEl.validate((valid, fields) => {
        if (valid) {
            const data = {
                ...ruleForm.value,
                limitDateTime: null,
                titleItems: titleItems.value,
                score: 0
            }
            console.log('submit!', data)
            examAdd(data)
                .then(res => {
                    if (res && res.code === 1) {
                        //提示
                        ElMessage({
                            message: '保存成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                                //跳转
                                router.push('/paper')
                            }
                        })
                    } else if (res) {
                        ElMessage({
                            message: res.message,
                            type: 'error'
                        })
                    }
                })
                .catch(err => {
                    console.error('接口错误详情:', err)
                    ElMessage({
                        message: err.message || '保存失败',
                        type: 'error'
                    })
                })
        }
    })
}
//重置表单功能
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 题目弹框相关
const showQuestionDialog = ref(false)
const currentTitleIdx = ref(0)
const questionForm = reactive({
  id: '',
  type: ''
})
const questionTypes = [
  { value: 1, label: '单选题' },
  { value: 2, label: '多选题' },
  { value: 3, label: '判断题' },
  { value: 4, label: '填空题' },
  { value: 5, label: '简答题' },
]
const questionList = ref<QuestionType[]>([])

function openQuestionDialog(idx: number) {
  currentTitleIdx.value = idx
  showQuestionDialog.value = true
  questionForm.id = ''
  questionForm.type = ''
  questionList.value = []
}
function closeQuestionDialog() {
  showQuestionDialog.value = false
}
async function queryQuestions() {
  // 调用真实接口，带上当前年级
  const params: any = {
    pageIndex: 1,
    pageSize: 10,
    id: questionForm.id,
    questionType: questionForm.type,
    level: ruleForm.value.level
  }
  const res = await QuestiontPage(params)
  if (res.code === 1 && res.response) {
    questionList.value = res.response.list
  } else {
    questionList.value = []
  }
}
function addQuestionToTitle(q: QuestionType) {
  titleItems.value[currentTitleIdx.value].questionItems.push({
    id: q.id,
    type: q.questionType,
    title: q.shortTitle || '',
    subjectId: q.subjectId ?? ruleForm.value.subjectId ?? '',
    analyze: '无', // 题目解析后端必填，直接赋默认值
    score: Number(q.score ?? 0),
    questionType: q.questionType ?? ''
  })
  showQuestionDialog.value = false
}

// 带类型的学科过滤函数
function filterSubjectByLevel(subjects: any[], level: number | string) {
  return subjects.filter((s) => s.level == level)
}

// 获取试卷详情并回显
onMounted(async () => {
  // 先加载学科列表
  await getsubjectList()
  const editId = route.query.id
  console.log('editId from route:', editId, typeof editId)
  if (!editId || isNaN(Number(editId))) {
    console.warn('无效的试卷id，跳过详情请求')
    return
  }
  // 编辑模式，获取详情并回显（使用新接口）
  try {
    const res = await axios.get(`/api/admin/exam/paper/select/${editId}`)
    console.log('试卷详情接口返回：', res.data)
    if (res.data && res.data.code === 1 && res.data.response) {
      const detail = res.data.response
      // 回显表单
      ruleForm.value = {
        ...ruleForm.value,
        ...detail,
        id: detail.id,
        level: String(detail.level),
        subjectId: String(detail.subjectId),
        paperType: String(detail.paperType),
        suggestTime: String(detail.suggestTime),
        name: detail.name,
        levelName: detail.levelName || ''
      }
      // 回显大题和题目
      titleItems.value = (detail.titleItems || []).map((t: any) => ({
        name: t.name,
        questionItems: (t.questionItems || []).map((q: any) => ({
          id: q.id,
          type: q.questionType ?? q.type ?? '',
          title: q.title ?? '',
          subjectId: q.subjectId ?? detail.subjectId,
          analyze: q.analyze || '无',
          score: Number(q.score ?? 0),
          questionType: q.questionType ?? q.type ?? 0
        }))
      }))
    } else {
      ElMessage.error(res.data?.message || '获取试卷详情失败')
    }
  } catch (e: any) {
    console.error('试卷详情接口异常:', e)
    ElMessage.error(e.message || '获取试卷详情失败')
  }
})
</script>

<style scoped>
.added-question-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 18px 24px 10px 24px;
  margin: 10px 0 18px 0;
}
.added-question-card {
  width: 220px;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  box-shadow: 0 1px 4px #f7f7f7;
  padding: 10px 12px 8px 12px;
  margin: 0;
  background: #fafbfc;
  transition: box-shadow 0.2s;
}
.added-question-card:hover {
  box-shadow: 0 4px 16px #e6e8eb;
}
.added-question-row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}
.added-question-label {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-right: 12px;
  min-width: 24px;
  text-align: center;
}
.added-question-id {
  color: #888;
  font-size: 14px;
  margin-right: 12px;
}
.added-question-type {
  color: #409EFF;
  font-size: 14px;
  margin-right: 12px;
}
.added-question-remove {
  margin-left: auto;
  color: #f56c6c !important;
  font-size: 14px;
}
.added-question-title {
  font-size: 15px;
  color: #222;
  margin-left: 32px;
  margin-top: 2px;
  word-break: break-all;
}
</style>